package main

import (
	"flag"
	"fmt"
	"github.com/hashicorp/consul/api"
	"github.com/satori/go.uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"net"
	"os"
	"os/signal"
	"project05/src/global"
	"project05/src/handler"
	"project05/src/initalize"
	"project05/src/proto"
	"syscall"
)

func main() {
	flag.Parse()

	initalize.InitConfig()
	initalize.InitDb()

	server := grpc.NewServer()
	proto.RegisterUserServiceServer(server, &handler.UserServer{})

	//注册健康检查
	grpc_health_v1.RegisterHealthServer(server, health.NewServer())
	//健康检查
	cfg := api.DefaultConfig()
	cfg.Address = fmt.Sprintf("%s:%d", global.SrvConfig.ConsulConf.Host, global.SrvConfig.ConsulConf.Port)
	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	check := api.AgentServiceCheck{
		GRPC:                           "192.168.61.84:8080", //要更改
		Timeout:                        "5s",
		Interval:                       "5s",
		DeregisterCriticalServiceAfter: "10s",
	}
	registation := new(api.AgentServiceRegistration)
	registation.Name = global.SrvConfig.Name
	serviceId := uuid.NewV4()
	serviceMyID := fmt.Sprintf("%s", serviceId)
	registation.ID = serviceMyID
	registation.Port = global.SrvConfig.Port
	registation.Address = global.SrvConfig.Host
	registation.Check = &check
	err = client.Agent().ServiceRegister(registation)
	if err != nil {
		panic(err)
	}

	lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", global.SrvConfig.Host, global.SrvConfig.Port))
	if err != nil {
		fmt.Println("net.Listen err", err)
		return
	}

	go func() {
		err = server.Serve(lis)
		if err != nil {
			fmt.Println("server.Serve err", err)
			return
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = client.Agent().ServiceDeregister(serviceMyID); err != nil {
		fmt.Println("注销失败")
	}
	fmt.Println("注销成功")
}
